package nettyTest.netty4test1.utptest;

import java.net.InetSocketAddress;

import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.DatagramPacket;
import io.netty.channel.socket.nio.NioDatagramChannel;
import io.netty.util.CharsetUtil;

/**
 * @Auther     : yxpweb
 * @Date       : 2021/8/15 21:40
 * @Description: UDP 的广播 多播 能发出去，服务端也能收到，但是服务端并不知道是谁发的，所以就不能收到服务端返回的消息。
 */
public class ChineseProverbClient {

	public void run(int port) throws Exception {
		EventLoopGroup group = new NioEventLoopGroup();
		try {
			Bootstrap b = new Bootstrap();
			b.group(group).channel(NioDatagramChannel.class).option(ChannelOption.SO_BROADCAST, true).handler(new ChineseProverbClientHandler());
			ChannelFuture ch = b.connect("255.255.255.255", 8080);
			Channel channel = ch.channel();
			ch.addListener(e -> {
				if(e.isSuccess()){
					
					channel.writeAndFlush(new DatagramPacket(Unpooled.copiedBuffer("谚语查询：", CharsetUtil.UTF_8), new InetSocketAddress("255.255.255.255", port)));
				}
			});
//			ch.writeAndFlush(new DatagramPacket(Unpooled.copiedBuffer("谚语查询：", CharsetUtil.UTF_8), new InetSocketAddress("255.255.255.255", port))).sync();
			channel.closeFuture().await(1000);
		} finally {
			group.shutdownGracefully();
		}
	}

	public static void main(String[] args) throws Exception {
		int port = 8080;
		if (args.length > 0) {
			try {
				port = Integer.parseInt(args[0]);
			} catch (NumberFormatException e) {
				e.printStackTrace();
			}
		}
		new ChineseProverbClient().run(port);
	}
}
